import os
import pyaudio
from vosk import Model, KaldiRecognizer
import json
import requests

import re

# 模型路径
model_path = "./vosk-model-small-cn-0.22"

# 加载模型
model = Model(model_path)

# 初始化识别器
recognizer = KaldiRecognizer(model, 160000)

# 初始化 PyAudio
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
                channels=1,
                rate=160000,
                input=True,
                frames_per_buffer=8000)
stream.start_stream()

# Ollama 的地址和端口（默认是 11434）
ollama_url = "http://localhost:11434/api/generate"

def contains_chinese(s):
    return re.search(r'[\u4e00-\u9fff]', s) is not None

def read_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        print(f'文件 {file_path} 未找到.')
    except Exception as e:
        print(f'读取文件时发生错误: {e}')

print("开始说话...")
while True:
    data = stream.read(2000)
    if recognizer.AcceptWaveform(data):
        result = recognizer.Result()
        text = json.loads(result)["text"]
        if contains_chinese(text) == False:
            continue
        print("识别结果:", text)

        # # 调用 Ollama API
        # data = {
        #     "model": "deepseek-r1:7b",
        #     "prompt": read_file('语料库.md')+text,
        #     "stream": True,
        # }

        # try:
        #     # 发送 POST 请求到 Ollama API，启用流式传输
        #     with requests.post(f"{ollama_url}", json=data, stream=True) as response:
        #         # 检查响应状态码
        #         if response.status_code == 200:
        #             if "application/x-ndjson" in response.headers.get("Content-Type").lower():
        #                 for line in response.iter_lines():
        #                     if line:
        #                         data = json.loads(line.decode('utf-8').strip())
        #                         print(data['response'], end="")
        #                         if data.get("done"):
        #                             print("\n")
        #                             break
        #         else:
        #             print("Error:", response.status_code, response.text)
        # except requests.exceptions.ConnectionError as e:
        #     print("无法连接到 Ollama API，请检查服务器是否启动并且 URL 是否正确。")
        #     print("详细错误信息:", e)